package org.yzh.web.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.yzh.web.component.handler.NettyWebSocketHandler;

@Component
@Slf4j
public class NettyWebServer {
    @Value ("${ws-server.jt808.port}")
    private  int port;
    public void run () {
        //boss线程组用来接收连接
        EventLoopGroup boss = new NioEventLoopGroup ();
        //worker线程组用来处理消息
        EventLoopGroup worker = new NioEventLoopGroup ();
        try {
            //辅助启动工具类
            ServerBootstrap bootstrap = new ServerBootstrap ();
            bootstrap.group (boss, worker).channel (NioServerSocketChannel.class).childHandler (new ChannelInitializer<SocketChannel> () {
                @Override
                protected void initChannel (SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline ();
                    //http编码解码器
                    pipeline.addLast (new HttpServerCodec ());
                    //分块传输
                    pipeline.addLast (new ChunkedWriteHandler ());
                    //块聚合
                    pipeline.addLast (new HttpObjectAggregator (1024 * 1024));
                    //协议处理器
                    pipeline.addLast (new WebSocketServerProtocolHandler ("/jtserver"));
                    //自定义的处理器
                    pipeline.addLast (new NettyWebSocketHandler ());
                }
            });
            //绑定端口，同步启动
            ChannelFuture future = bootstrap.bind (port).sync ();
            future.channel ().closeFuture ().sync ();
            log.info ("jt808-ws-server启动成功：{}",port);
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            boss.shutdownGracefully ();
            worker.shutdownGracefully ();
        }
    }
    public void start (){
        run ();
    }
}